﻿/* **
 * WebQ - a Web Questionare / Survey Framework
 * Andrew Adhi Ariane Murniadi / 2009
 * GPL
 * $Id$
 *									** */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebQ.Core;
using WebQ.Visualizers;

namespace WebQ {

	/// <summary>
	/// The base ASP.Net control to be placed on the WebForm
	/// </summary>
	[DefaultProperty ( "Text" )]
	[ToolboxData ( "<{0}:WebQControl runat=server></{0}:WebQControl>" )]
	public class WebQControl : CompositeControl {
		
		private WebQEntityCollection m_entities = new WebQEntityCollection ();

		/// <summary>
		/// Data for questionaire creation
		/// </summary>
		[PersistenceMode ( PersistenceMode.InnerProperty )]
		public WebQEntityCollection Data {
			get { return m_entities; }
		}

		/// <summary>
		/// Default Constructor
		/// </summary>
		public WebQControl () {

		}

		/// <summary>
		/// Overrides base implementation. The new implementation added postback value processing before
		/// invoking base OnInit method
		/// </summary>
		/// <param name="e">argument to pass to event</param>
		protected override void OnInit ( EventArgs e ) {

			if ( Page.IsPostBack ) {
				WebQPostbackExtractor postbackExtractor = new WebQPostbackExtractor ( this.ID + this.IdSeparator, Page.Request.Form );

				foreach ( WebQEntity en in m_entities ) {
					en.Configuration.Visualizer.ExtractAnswers ( en.QAItem, postbackExtractor.ExtractPostbackData () );
				}
			}

			base.OnInit ( e );
		}

		/// <summary>
		/// Produces dynamic control tree and adding them to the parent controls
		/// </summary>
		protected override void CreateChildControls () {
			Controls.Clear ();

			foreach ( WebQEntity entity in m_entities ) {
				foreach ( Control ctrl in entity.Configuration.Visualizer.GetChildControls ( entity.QAItem ) ) {
					Controls.Add ( ctrl );
				}
			}
		}
	}
}
